package com.vanke.devops.domain.manager.ssh.impl;

import com.vanke.devops.domain.manager.ssh.SSHConfig;
import com.vanke.devops.domain.manager.ssh.SSHManager;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.DisconnectReason;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author 陈景阳
 * @since 2018/6/11
 */
@Service
public class SSHManagerImpl implements SSHManager{
    @Override
    public void updateHostname(String hostname, SSHConfig config) {
        try {
            SSHClient client = new SSHClient();
            try {
                client.connect(config.getHost());
            } catch (TransportException e) {
                if (e.getDisconnectReason() == DisconnectReason.HOST_KEY_NOT_VERIFIABLE) {
                    String msg = e.getMessage();
                    String[] split = msg.split("`");
                    String vc = split[3];
                    client = new SSHClient();
                    client.addHostKeyVerifier(vc);
                    client.connect(config.getHost(), 22);
                } else {
                    e.printStackTrace();
                }
            }
            client.authPassword(config.getUsername(), config.getPassword());
            Session session = client.startSession();
            session.exec("hostnamectl --static set-hostname " + hostname);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
